﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Wise.Util;

namespace Wise.Entities
{
    public class FileHelper:HelperBase<FileHelper>
    {
        static readonly Regex _RegBIN = new Regex("(DEBUG|Release|BIN)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        static bool IsBinDir(string dir)
        {
            return _RegBIN.IsMatch(dir);
        }
        private static string CurrentDirectory = null;

        public static string GetCurrentDirectory()
        {
            if(CurrentDirectory==null)
            {
                string binDir = null;
                binDir = Environment.CurrentDirectory;
                while (IsBinDir(binDir))
                {
                    binDir = System.IO.Directory.GetParent(binDir).FullName;
                }
                CurrentDirectory = binDir;
            }
            return CurrentDirectory;
        }

        public static string ToAbsolute(string relativePath)
        {
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(GetCurrentDirectory());
            string[] dirs= relativePath.Split("\\/".ToArray(), StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dirs.Length; i++)
            {
                string d = dirs[i];
                if(d=="."|| d == "~")
                {
                    directory= new System.IO.DirectoryInfo(GetCurrentDirectory());
                }
                else if(d=="..")
                {
                    directory = directory.Parent;
                }
                else if(i==dirs.Length-1)
                {
                    return System.IO.Path.Combine(directory.FullName, d);
                }
                else
                {
                    directory = directory.GetDirectories(d, System.IO.SearchOption.TopDirectoryOnly).FirstOrDefault();
                }
                if (directory == null)
                    return GetCurrentDirectory();
            }
            return directory.FullName;
        }
    }
}
